const mysql = require("mysql2");
const express = require("express");
const bodyParser = require("body-parser");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const cors = require('cors');

const connection = mysql.createConnection({
  host: "localhost", // 数据库主机地址
  user: "root", // 数据库用户名
  password: "Pass@word!1", // 数据库密码
  port: 3306,
  database: "remote_consultation", // 数据库名
  connectTimeout: 10000, // 设置连接超时为10秒
});
connection.connect((err) => {
  if (err) {
    console.error("连接失败: " + err);
  } else {
    console.log("数据库连接成功");
  }
});

const sql = "SELECT * FROM pat_drug";
connection.query(sql, (err, results, fields) => {
  if (err) {
    console.log("查询失败" + err.stack);
    return;
  }
  console.log("查询结果", results);
});

const app = express();
app.use(bodyParser.json());
app.use(express.json());
app.use(cors());

app.get("/query-drugs", (req, res) => {
  const { pat_id } = req.query;
  if (!pat_id) {
    return res.status(400).send("缺少参数pat_id");
  }
  const query = "SELECT * FROM pat_drug WHERE pat_id = ?";
  connection.query(query, [pat_id], (error, results) => {
    if (error) {
      return res.status(500).send("Error querying database");
    }
    res.json(results);
  });
});

const promisePool = connection.promise();
const JWT_SECRET = "your_jwt_secret";

app.post("/login", async (req, res) => {
  console.log(req, "req");
  const { username, password } = req.body;

  if (!username || !password) {
    return res.status(400).send("Username and password are required");
  }

  try {
    // 查询数据库获取用户信息
    const [rows] = await promisePool.query(
      "SELECT * FROM login WHERE username = ?",
      [username]
    );

    // Debug log: 查看查询结果
    console.log("Database response:", rows);

    if (rows.length === 0) {
      return res.status(401).send("Invalid username or password");
    }
    const options = {
      expiresIn: "1h", // Token有效期为1小时
    };
    const user = rows[0];

    // Debug log: 查看存储的密码
    console.log("Stored password hash:", user.password);
    console.log("Stored password hash:", password);

    // 使用 bcrypt 比较输入的密码和存储的加密密码
    const match = await bcrypt.compare(password, user.password);

    // Debug log: 是否匹配
    console.log("Password match result:", match);

    if (!match) {
      res.status(200).json({
        message: "登录成功！",
        user: {
          id: user.id,
          username: user.username,
          token: jwt.sign(user, JWT_SECRET, options),
        },
      });
    } else {
      res.status(401).send("Invalid username or password");
    }
  } catch (err) {
    console.error("Error during login:", err);
    res.status(500).send("Internal server error");
    res.status(500).json({
      message: err,
    });
  }
});

const PORT = 3000;
app.listen(PORT, () => {
  console.log(111);
  console.log(`1111 ${PORT}`);
});
